//
//  LWXDownloadManager.m
//  EPA
//
//  Created by lanou3g on 16/4/28.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "LWXDownloadManager.h"
#import "LWXMusicDownloadTask.h"
// 创建一个私有的类
@interface DownloadManagerTask : NSObject
@property (nonatomic, strong) LWXRadioListModel *model;

@property (nonatomic, strong) LWXMusicDownloadTask *downloadTask;


@end


@implementation DownloadManagerTask

- (NSString *)description {
    return self.model.title;
}



@end


@implementation LWXDownloadManager

+ (instancetype)shareManager {
    static LWXDownloadManager *downloadManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!downloadManager) {
            downloadManager = [LWXDownloadManager new];
            downloadManager.array = [NSMutableArray new];
        }
    });
    return downloadManager;
}
// 使用字典 key 值一样了就不用再下载了


// 添加下载任务
- (void)addDownloadTask:(LWXRadioListModel *)model Progress:(ProgressBlock)proBlock Complete:(CompleteBlock)comBlock {
    
    for (DownloadManagerTask *task in self.array) {
        if ([task.model.title isEqualToString:model.title]) {
            // 包括就不下载
            return;
        }
    }
    
    //    下载任务
    LWXMusicDownloadTask *musicTask = [[LWXMusicDownloadTask alloc]init];
    [musicTask downloadUrl:[NSURL URLWithString:model.musicUrl] progressBlock:proBlock complete:comBlock];
    
    
    // 添加到数组中
    DownloadManagerTask *downloadManagerTask = [DownloadManagerTask new];
    downloadManagerTask.model = model;
    downloadManagerTask.downloadTask = musicTask;
    [self.array addObject:downloadManagerTask];
   
}

// 当前下载任务个数

- (NSInteger)count {
    return self.array.count;
}
// 取标题
- (NSString *)getTitleWithIndex:(NSInteger)index {
    DownloadManagerTask *task = self.array[index];
    return task.model.title;
}
// 设置 block
- (void)setProgressBlock:(ProgressBlock)proBlock CompleteBlock:(CompleteBlock)comBlock Index:(NSInteger)index {
    DownloadManagerTask *task = self.array[index];
    [task.downloadTask setProgressBlock:proBlock];
    [task.downloadTask setCompleteBlock:^(NSString *path) {
        [self.array removeObjectAtIndex:index];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"downloadReloadData" object:nil];
    }];
}





@end
